﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CodeCarvings.Piczard;
using CodeCarvings.Piczard.Filters.Watermarks;
using RentHouse.Common;
using RentHouse.DTO;
using RentHouse.IService;

namespace RentHouse.Admin.Controllers
{
    public class HouseController : Controller
    {
        private readonly IHouseService _houseService;
        private readonly IIdNameService _idNameService;
        private readonly IRegionService _regionService;
        private readonly ICommunityService _communityService;
        public HouseController(IHouseService houseService,IIdNameService idNameService,IRegionService regionService,ICommunityService communityService)
        {
            this._houseService = houseService;
            this._idNameService = idNameService;
            this._regionService = regionService;
            this._communityService = communityService;
        }
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 根据传过来的typeId判断显示租房类型
        /// </summary>
        /// <param name="start"></param>
        /// <param name="length"></param>
        /// <param name="communityName"></param>
        /// <param name="typeId"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetHouseList(int start,int length,string communityName, int typeId)
        {
            int count = 0;
            var list= _houseService.GetList(start,length,communityName,typeId, ref count);
            var result = new
            {
                data = list,
                recordsTotal = count,
                recordsFiltered = count,
            };
            return Json(result);
        }
        /// <summary>
        /// 显示上传图片界面
        /// </summary>
        /// <returns></returns>
        public ActionResult UploadPic()
        {
            return View();
        }
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="houseId"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        
        public ActionResult UploadPic(int houseId, HttpPostedFileBase file)
        {
            //1.点击上传图片图标弹窗展示上传图片视图
            //2.点击图片进行上传，提交时将houseId和HttpPostedFileBase file作为参数传递后台(获取url中houseid)参照下方链接
            //3.下载第三方组件CodeCarvings.Piczard,确定一个水印图片自己选择( / images / watermark.jpg)，图片上传路径文件夹
            //4.写对应接口以及实现方法、返回结果到前台
            //5.前台根据uploader.on(‘uploadSuccess’, function(file, response)反馈上传结果
            //6.点击展示大图效果（jQuerylightbox插件）
            //HouseDTO house = houseService.GetDTOById(houseId);
            //if (house == null)
            //{
            //    //return Json(new AjaxResult { Status = "error", ErrorMsg = "获取不到房源信息" });
            //    throw new Exception("获取不到房源信息");
            //}

            //month月，minute
            string md5 = CommonHelper.CalcMD5(file.InputStream);
            string ext = Path.GetExtension(file.FileName);
            string path = "/upload/" + DateTime.Now.ToString("yyyy/MM/dd") + "/" + md5 + ext;// /upload/2017/07/07/afadsfa.jpg
            string thumbPath = "/upload/" + DateTime.Now.ToString("yyyy/MM/dd") + "/" + md5 + "_thumb" + ext;
            string fullPath = HttpContext.Server.MapPath("~" + path);//d://22/upload/2017/07/07/afadsfa.jpg
            string thumbFullPath = HttpContext.Server.MapPath("~" + thumbPath);
            new FileInfo(fullPath).Directory.Create();//尝试创建可能不存在的文件夹

            file.InputStream.Position = 0;//指针复位
                                          //file.SaveAs(fullPath);//SaveAs("d:/1.jpg");
                                          //缩略图
            ImageProcessingJob jobThumb = new ImageProcessingJob();
            jobThumb.Filters.Add(new FixedResizeConstraint(200, 200));//缩略图尺寸200*200
            jobThumb.SaveProcessedImageToFileSystem(file.InputStream, thumbFullPath);

            file.InputStream.Position = 0;//指针复位

            //水印
            ImageWatermark imgWatermark = new ImageWatermark(HttpContext.Server.MapPath("~/img/lou.png"));
            imgWatermark.ContentAlignment = System.Drawing.ContentAlignment.BottomRight;//水印位置
            imgWatermark.Alpha = 50;//透明度，需要水印图片是背景透明的png图片
            ImageProcessingJob jobNormal = new ImageProcessingJob();
            jobNormal.Filters.Add(imgWatermark);//添加水印
            jobNormal.Filters.Add(new FixedResizeConstraint(600, 600));
            jobNormal.SaveProcessedImageToFileSystem(file.InputStream, fullPath);
            HousePicDTO picDTO = new HousePicDTO
            {
                HouseId = houseId,
                ThumbUrl = thumbPath,
                Url = path
            };
            return Json(_houseService.AddHousePic(picDTO));


    
        }

        public ActionResult LookPic(int id)
        {
            var housePicDto = _houseService.GetPicList(id);
            return View(housePicDto);
        }

        /// <summary>
        /// 省市联动
        /// </summary>
        /// <param name="regionId"></param>
        /// <returns></returns>

        [HttpPost]
        public ActionResult GetCommunities(long regionId)
        {
            return Json(_communityService.GetCommuities(regionId));
        }


        /// <summary>
        /// 显示添加房源页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Create()
        {
            var user = User as  MyFormsPrincipal<LoginAdminDTO>;
            long cityId = user.UserData.CityId;
            //区域的下拉框
            //Idnames   4个下拉框
            ViewBag.RegionList = _regionService.GetRegionList(cityId).Select(e=>new SelectListItem() { 
            Text=e.Name,
            Value=e.Id.ToString()
            }).ToList();   //因为是泛型集合所以要toList(),如果前台是IEnumerable则不用

            //房型下拉框
            ViewBag.RoomTypeList = _idNameService.GetIdNameList(IdNameEnum.户型).Select(e=>new SelectListItem() { Text=e.Name,Value=e.Id.ToString()}).ToList();
            //状态下拉框
            ViewBag.StatusList = _idNameService.GetIdNameList(IdNameEnum.房屋状态).Select(e => new SelectListItem() { Text = e.Name, Value = e.Id.ToString() }).ToList();
            //装修状态下拉框
            ViewBag.DecorateStatusList = _idNameService.GetIdNameList(IdNameEnum.装修状态).Select(e => new SelectListItem() { Text = e.Name, Value = e.Id.ToString() }).ToList();
            //房屋类型下拉框
            ViewBag.TypeList = _idNameService.GetIdNameList(IdNameEnum.房屋类型).Select(e => new SelectListItem() { Text = e.Name, Value = e.Id.ToString() }).ToList();

            return View(_houseService.GetAttachmentList());
        }
        /// <summary>
        /// 添加房源
        /// </summary>
        /// <param name="houseAddDTO"></param>
        /// <returns></returns>
        /// 
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(HouseAddDTO houseAddDTO)
        {
            return Json(_houseService.AddHouse(houseAddDTO));
        }

        /// <summary>
        /// 显示添加房源页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Edit(long id)
        {
            var user = User as MyFormsPrincipal<LoginAdminDTO>;
            long cityId = user.UserData.CityId;
            var house = _houseService.GetHouseInfo(id);
            //区域的下拉框
            //Idnames   4个下拉框
            ViewBag.RegionList = _regionService.GetRegionList(cityId).Select(e => new SelectListItem()
            {
                Text = e.Name,
                Value = e.Id.ToString(),
                Selected=e.Id==house.RegionId
            }).ToList();   //因为是泛型集合所以要toList(),如果前台是IEnumerable则不用
         
            
        
            //房型下拉框
            ViewBag.RoomTypeList = _idNameService.GetIdNameList(IdNameEnum.户型).Select(e => new SelectListItem() { Text = e.Name, Value = e.Id.ToString() ,Selected=e.Id==house.RoomTypeId}).ToList();
            //状态下拉框
            ViewBag.StatusList = _idNameService.GetIdNameList(IdNameEnum.房屋状态).Select(e => new SelectListItem() { Text = e.Name, Value = e.Id.ToString(),Selected= e.Id==house.StatusId}).ToList();
            //装修状态下拉框
            ViewBag.DecorateStatusList = _idNameService.GetIdNameList(IdNameEnum.装修状态).Select(e => new SelectListItem() { Text = e.Name, Value = e.Id.ToString(), Selected = e.Id == house.DecorateStatusId }).ToList();
            //房屋类型下拉框
            ViewBag.TypeList = _idNameService.GetIdNameList(IdNameEnum.房屋类型).Select(e => new SelectListItem() { Text = e.Name, Value = e.Id.ToString(), Selected = e.Id == house.TypeId }).ToList();

            return View(house);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Update(HouseEditDTO editDTO)
        {
             return Json(_houseService.Update(editDTO));
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Delete(long id)
        {
            return Json(_houseService.Delete(id));
        }

        /// <summary>
        /// 生成房源页面的静态页
        /// </summary>
        /// <returns></returns>
        public ActionResult CreateStaticPage()
        {
            //1.获取要存放静态页面的位置
            string htmlUrl = CommonHelper.GetStaticPage();

            //2.获取系统中所有的房源信息
            var list = _houseService.GetDetailDTOList();

            //3.根据当前模板和对应的房源信息生成HTML
            foreach (var item in list)
            {
                string html = MVCHelper.RenderViewToString(this.ControllerContext, "/Views/House/Detail.cshtml", item);

                //4.将生成的html按照位置输出
                System.IO.File.WriteAllText(htmlUrl+item.Id+".html",html);
            }
            return Json(new AjaxResult(ResultState.Success, "生成成功"));
        }
    }
}